package main

import (
	"container/list"
	"fmt"
	"math"
)

func main() {
	asteroids := []int{8, -8}
	res := asteroidCollision(asteroids)
	fmt.Println(res)
}

func asteroidCollision(asteroids []int) []int {
	var res []int
	stack := list.New()
	for _, asteroid := range asteroids {
		if stack.Len() == 0 {
			stack.PushBack(asteroid)
			continue
		}
		//fmt.Println(asteroid)
		crushLeft := asteroid
		for stack.Len() > 0 && stack.Back().Value.(int) > 0 && crushLeft < 0 { //栈顶行星向右，遍历到的行星向左才能相撞
			top := stack.Remove(stack.Back()).(int)
			crushLeft = crush(top, crushLeft)
			if crushLeft == 0 {
				break
			}
		}
		if crushLeft != 0 {
			stack.PushBack(crushLeft)
		}
	}
	for node := stack.Front(); node != nil; {
		res = append(res, node.Value.(int))
		node = node.Next()
	}
	return res
}

func crush(top, asteroid int) int {
	if math.Abs(float64(top)) > math.Abs(float64(asteroid)) {
		return top
	} else if math.Abs(float64(top)) < math.Abs(float64(asteroid)) {
		return asteroid
	} else {
		return 0
	}
}
